﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;

/// <summary>
/// Class1 的摘要说明
/// </summary>
public class Big_file_upload
{
	public Big_file_upload()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}
    public int File_part_count(string dir, string name, int total)  //获得已上传连续文件数量
    {
        string part = "";
        int file_num = 0;
        for (int j = 1; j <= total; ++j)
        {
            part = Path.Combine(dir, name + "_" + j);
            if (System.IO.File.Exists(part) == true)
            {
                ++file_num;
            }
            else
            {
                break;  //获得断点
            }
        }
        return file_num;
    }

    public string Get_file_md5(string filename,string dir,int shardSize)
    {
        //string fileName = "1.1 材料力学的任务.mp4";
        //string dir = Server.MapPath("~/Upload");
        //获得文件MD5的值
        string msg = "";
            try
            {
            //int shardSize = 2 * 1024 * 1024;		//以2MB为一个分片

            string file_N = Path.Combine(dir, filename);
            FileInfo temp_file_info = new FileInfo(file_N);
            long start = 0;
            long end = Math.Min((long)(temp_file_info.Length), start + shardSize); //大文件取第一片生成临时文件
            string temp_file_name = "";
            if (temp_file_info.Length > shardSize)
            {
                temp_file_name = Path.Combine(dir, filename + "_temp");
                FileStream file = new FileStream(file_N, System.IO.FileMode.Open);
                BinaryReader br = new BinaryReader(file);
                byte[] bs = br.ReadBytes(Convert.ToInt32(end));
                br.Close();
                file.Close();
                FileStream temp_file = new FileStream(temp_file_name, FileMode.Create, FileAccess.Write);
                temp_file.Write(bs, 0, bs.Length);
                temp_file.Close();
            }
            else
            {
                temp_file_name = Path.Combine(dir, filename);
            }
            FileStream file1 = new FileStream(temp_file_name, System.IO.FileMode.Open);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(file1);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            msg = sb.ToString();
            file1.Close();
            if (temp_file_info.Length > shardSize)
            {
                System.IO.File.Delete(temp_file_name);//删除临时生成的文件
            }
        }
            catch (Exception)
            {
                msg="error";
            }
        return (msg);
      }
}